<template>
	<view class="address-edit-container">
		<view class="header">
			<text class="title">{{isEdit ? '编辑收货地址' : '新增收货地址'}}</text>
		</view>
		
		<!-- 地址表单 -->
		<view class="address-form">
			<view class="form-item">
				<text class="label">收货人</text>
				<input type="text" v-model="addressForm.name" placeholder="请输入收货人姓名" />
			</view>
			
			<view class="form-item">
				<text class="label">手机号码</text>
				<input type="number" v-model="addressForm.phone" placeholder="请输入手机号码" maxlength="11" />
			</view>
			
			<view class="form-item">
				<text class="label">所在地区</text>
				<view class="region-picker" @click="showRegionPicker">
					<text v-if="regionText">{{regionText}}</text>
					<text v-else class="placeholder">请选择所在地区</text>
					<text class="arrow">></text>
				</view>
			</view>
			
			<view class="form-item">
				<text class="label">详细地址</text>
				<textarea v-model="addressForm.detail" placeholder="街道、楼牌号等" />
			</view>
			
			<view class="form-item switch-item">
				<text class="label">设为默认地址</text>
				<switch :checked="addressForm.isDefault" @change="setDefaultChange" color="#FF5151" />
			</view>
		</view>
		
		<!-- 保存按钮 -->
		<view class="btn-wrapper">
			<button class="save-btn" @click="saveAddress">保存</button>
		</view>
		
		<!-- 区域选择器弹窗 -->
		<view class="region-picker-popup" v-if="showRegion">
			<view class="region-mask" @click="hideRegionPicker"></view>
			<view class="region-content">
				<view class="region-header">
					<text class="cancel" @click="hideRegionPicker">取消</text>
					<text class="title">选择地区</text>
					<text class="confirm" @click="confirmRegion">确定</text>
				</view>
				<view class="region-tabs">
					<view 
						class="tab-item" 
						v-for="(item, index) in ['省份', '城市', '区县']" 
						:key="index"
						:class="{ active: regionTabIndex === index }"
						@click="switchRegionTab(index)"
					>
						<text>{{selectedRegion[index] ? selectedRegion[index].name : item}}</text>
					</view>
				</view>
				<scroll-view class="region-list" scroll-y>
					<view 
						class="region-item" 
						v-for="(item, index) in currentRegionList" 
						:key="index"
						:class="{ active: isRegionSelected(item) }"
						@click="selectRegionItem(item)"
					>
						<text>{{item.name}}</text>
						<text v-if="isRegionSelected(item)" class="check-icon">✓</text>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	import { addressApi } from '@/api/index';
	
	// 模拟地区数据，实际项目中应该从服务器获取
	const mockProvinces = [
		{ id: 1, name: '北京市' },
		{ id: 2, name: '上海市' },
		{ id: 3, name: '广东省' },
		{ id: 4, name: '江苏省' },
		{ id: 5, name: '浙江省' }
	];
	
	const mockCities = {
		1: [{ id: 101, name: '北京市', pid: 1 }],
		2: [{ id: 201, name: '上海市', pid: 2 }],
		3: [
			{ id: 301, name: '广州市', pid: 3 },
			{ id: 302, name: '深圳市', pid: 3 },
			{ id: 303, name: '珠海市', pid: 3 }
		],
		4: [
			{ id: 401, name: '南京市', pid: 4 },
			{ id: 402, name: '苏州市', pid: 4 },
			{ id: 403, name: '无锡市', pid: 4 }
		],
		5: [
			{ id: 501, name: '杭州市', pid: 5 },
			{ id: 502, name: '宁波市', pid: 5 },
			{ id: 503, name: '温州市', pid: 5 }
		]
	};
	
	const mockDistricts = {
		101: [
			{ id: 10101, name: '东城区', pid: 101 },
			{ id: 10102, name: '西城区', pid: 101 },
			{ id: 10103, name: '朝阳区', pid: 101 },
			{ id: 10104, name: '海淀区', pid: 101 }
		],
		201: [
			{ id: 20101, name: '黄浦区', pid: 201 },
			{ id: 20102, name: '徐汇区', pid: 201 },
			{ id: 20103, name: '长宁区', pid: 201 },
			{ id: 20104, name: '静安区', pid: 201 }
		],
		301: [
			{ id: 30101, name: '越秀区', pid: 301 },
			{ id: 30102, name: '海珠区', pid: 301 },
			{ id: 30103, name: '荔湾区', pid: 301 },
			{ id: 30104, name: '天河区', pid: 301 }
		],
		302: [
			{ id: 30201, name: '福田区', pid: 302 },
			{ id: 30202, name: '罗湖区', pid: 302 },
			{ id: 30203, name: '南山区', pid: 302 },
			{ id: 30204, name: '宝安区', pid: 302 }
		]
	};
	
	export default {
		data() {
			return {
				isEdit: false,
				addressId: null,
				addressForm: {
					name: '',
					phone: '',
					province: '',
					city: '',
					district: '',
					detail: '',
					isDefault: false
				},
				// 区域选择相关
				showRegion: false,
				regionTabIndex: 0,
				selectedRegion: [null, null, null],
				currentRegionList: []
			}
		},
		computed: {
			regionText() {
				if (this.addressForm.province && this.addressForm.city && this.addressForm.district) {
					return `${this.addressForm.province} ${this.addressForm.city} ${this.addressForm.district}`;
				}
				return '';
			}
		},
		onLoad(options) {
			if (options.id) {
				this.isEdit = true;
				this.addressId = options.id;
				this.getAddressDetail();
			} else {
				this.currentRegionList = mockProvinces;
			}
		},
		methods: {
			// 获取地址详情
			async getAddressDetail() {
				try {
					uni.showLoading({
						title: '加载中...'
					});
					
					const res = await addressApi.getAddressDetail(this.addressId);
					const addressData = res.data;
					
					if (addressData) {
						this.addressForm = { ...addressData };
						
						// 根据地址信息设置已选择的区域
						this.initSelectedRegion();
					}
					
				} catch (e) {
					console.error('获取地址详情失败', e);
					uni.showToast({
						title: '获取地址详情失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			
			// 初始化已选择的区域
			initSelectedRegion() {
				// 初始化省份列表
				this.currentRegionList = mockProvinces;
				
				// 寻找省份
				const province = mockProvinces.find(item => item.name === this.addressForm.province);
				if (province) {
					this.selectedRegion[0] = province;
					
					// 加载城市列表
					this.currentRegionList = mockCities[province.id] || [];
					
					// 寻找城市
					const city = this.currentRegionList.find(item => item.name === this.addressForm.city);
					if (city) {
						this.selectedRegion[1] = city;
						
						// 加载区县列表
						this.currentRegionList = mockDistricts[city.id] || [];
						
						// 寻找区县
						const district = this.currentRegionList.find(item => item.name === this.addressForm.district);
						if (district) {
							this.selectedRegion[2] = district;
						}
					}
				}
				
				// 重置当前区域列表为省份列表
				this.currentRegionList = mockProvinces;
				this.regionTabIndex = 0;
			},
			
			// 显示区域选择器
			showRegionPicker() {
				this.showRegion = true;
				
				// 如果没有选择过任何区域，显示省份列表
				if (!this.selectedRegion[0]) {
					this.currentRegionList = mockProvinces;
					this.regionTabIndex = 0;
				}
			},
			
			// 隐藏区域选择器
			hideRegionPicker() {
				this.showRegion = false;
			},
			
			// 切换区域选择器的标签
			switchRegionTab(index) {
				if (index === 0) {
					this.currentRegionList = mockProvinces;
				} else if (index === 1) {
					if (this.selectedRegion[0]) {
						this.currentRegionList = mockCities[this.selectedRegion[0].id] || [];
					} else {
						return; // 如果没有选择省份，不允许切换到城市标签
					}
				} else if (index === 2) {
					if (this.selectedRegion[1]) {
						this.currentRegionList = mockDistricts[this.selectedRegion[1].id] || [];
					} else {
						return; // 如果没有选择城市，不允许切换到区县标签
					}
				}
				
				this.regionTabIndex = index;
			},
			
			// 选择区域项目
			selectRegionItem(item) {
				this.selectedRegion[this.regionTabIndex] = item;
				
				// 清除之后的选择
				for (let i = this.regionTabIndex + 1; i < this.selectedRegion.length; i++) {
					this.selectedRegion[i] = null;
				}
				
				// 如果选择了省份，切换到城市选择
				if (this.regionTabIndex === 0) {
					this.currentRegionList = mockCities[item.id] || [];
					this.regionTabIndex = 1;
				} 
				// 如果选择了城市，切换到区县选择
				else if (this.regionTabIndex === 1) {
					this.currentRegionList = mockDistricts[item.id] || [];
					this.regionTabIndex = 2;
				}
				// 如果选择了区县，关闭选择器
				else if (this.regionTabIndex === 2) {
					this.confirmRegion();
				}
			},
			
			// 确认区域选择
			confirmRegion() {
				if (this.selectedRegion[0]) {
					this.addressForm.province = this.selectedRegion[0].name;
					
					if (this.selectedRegion[1]) {
						this.addressForm.city = this.selectedRegion[1].name;
						
						if (this.selectedRegion[2]) {
							this.addressForm.district = this.selectedRegion[2].name;
						}
					}
				}
				
				this.hideRegionPicker();
			},
			
			// 判断某个区域项目是否被选中
			isRegionSelected(item) {
				const selected = this.selectedRegion[this.regionTabIndex];
				return selected && selected.id === item.id;
			},
			
			// 设置默认地址状态改变
			setDefaultChange(e) {
				this.addressForm.isDefault = e.detail.value;
			},
			
			// 保存地址
			async saveAddress() {
				// 表单验证
				if (!this.addressForm.name) {
					uni.showToast({
						title: '请输入收货人姓名',
						icon: 'none'
					});
					return;
				}
				
				if (!this.addressForm.phone) {
					uni.showToast({
						title: '请输入手机号码',
						icon: 'none'
					});
					return;
				}
				
				if (!/^1\d{10}$/.test(this.addressForm.phone)) {
					uni.showToast({
						title: '手机号码格式不正确',
						icon: 'none'
					});
					return;
				}
				
				if (!this.addressForm.province || !this.addressForm.city || !this.addressForm.district) {
					uni.showToast({
						title: '请选择所在地区',
						icon: 'none'
					});
					return;
				}
				
				if (!this.addressForm.detail) {
					uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					});
					return;
				}
				
				try {
					uni.showLoading({
						title: '保存中...'
					});
					
					if (this.isEdit) {
						// 更新地址
						await addressApi.updateAddress({
							...this.addressForm,
							id: this.addressId
						});
					} else {
						// 新增地址
						await addressApi.addAddress(this.addressForm);
					}
					
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					});
					
					// 返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
					
				} catch (e) {
					console.error('保存地址失败', e);
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			}
		}
	}
</script>

<style lang="scss">
.address-edit-container {
	padding: 20rpx;
	min-height: 100vh;
	background-color: #f8f8f8;
}

.header {
	padding: 20rpx 0;
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
}

.address-form {
	margin-top: 20rpx;
	background-color: #fff;
	border-radius: 15rpx;
	padding: 0 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	
	.form-item {
		display: flex;
		align-items: flex-start;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
		
		&:last-child {
			border-bottom: none;
		}
		
		.label {
			width: 150rpx;
			font-size: 28rpx;
			color: #333;
			padding-top: 10rpx;
		}
		
		input, textarea, .region-picker {
			flex: 1;
		}
		
		input {
			height: 60rpx;
			font-size: 28rpx;
			color: #333;
		}
		
		textarea {
			width: 100%;
			height: 120rpx;
			font-size: 28rpx;
			color: #333;
		}
		
		.region-picker {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 60rpx;
			
			.placeholder {
				color: #999;
				font-size: 28rpx;
			}
			
			.arrow {
				color: #ccc;
				font-size: 28rpx;
			}
		}
		
		&.switch-item {
			align-items: center;
		}
	}
}

.btn-wrapper {
	margin-top: 60rpx;
	padding: 0 20rpx;
	
	.save-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #FF5151;
		color: #fff;
		font-size: 32rpx;
		border-radius: 45rpx;
	}
}

.region-picker-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 999;
	
	.region-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
	}
	
	.region-content {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		height: 60vh;
		border-radius: 20rpx 20rpx 0 0;
		overflow: hidden;
		
		.region-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 30rpx;
			border-bottom: 1rpx solid #f5f5f5;
			
			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
			
			.cancel, .confirm {
				font-size: 28rpx;
				padding: 10rpx;
			}
			
			.cancel {
				color: #999;
			}
			
			.confirm {
				color: #FF5151;
			}
		}
		
		.region-tabs {
			display: flex;
			padding: 20rpx 30rpx;
			border-bottom: 1rpx solid #f5f5f5;
			
			.tab-item {
				margin-right: 40rpx;
				padding: 10rpx 0;
				font-size: 28rpx;
				color: #999;
				position: relative;
				
				&.active {
					color: #FF5151;
					font-weight: bold;
					
					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 0;
						right: 0;
						height: 4rpx;
						background-color: #FF5151;
						border-radius: 2rpx;
					}
				}
			}
		}
		
		.region-list {
			height: calc(60vh - 170rpx);
			
			.region-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx 30rpx;
				font-size: 28rpx;
				color: #333;
				
				&.active {
					color: #FF5151;
				}
				
				.check-icon {
					color: #FF5151;
				}
			}
		}
	}
}
</style> 